package com.myfoon.action.backing.context;

import com.myfoon.model.entity.Location;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MapBean {    
    public MapBean() {    
    }
    
    public List<Location> findLocations(String prefix, String sllValue) {
        List<Location> searchResults = new ArrayList<Location>();
        
        if (prefix.equals(""))
            return searchResults;
        
        if (sllValue != null && sllValue.length() >= 4) {
            sllValue = sllValue.substring(1, sllValue.length() - 1);
            sllValue = sllValue.replaceAll(" ", "");
        }

        URL url;
        URLConnection connection;
        String line;
        StringBuilder builder = null;
        BufferedReader reader = null;
        String urlStr;

        try {
            prefix = URLEncoder.encode(prefix, "UTF-8");

            urlStr =
                    "http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=large&mrt=blended";
            urlStr = urlStr + "&q=" + prefix;

            if (sllValue != null && sllValue.length() > 4) {
                System.out.println(sllValue);                
                urlStr = urlStr + "&sll=" + sllValue;
            }

            url = new URL(urlStr);
            connection = url.openConnection();
            connection.addRequestProperty("Referer",
                                          "http://www.mysite.com/index.html");

            builder = new StringBuilder();
            reader =
                    new BufferedReader(new InputStreamReader(connection.getInputStream()));

            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            JSONObject json;
            json = new JSONObject(builder.toString());


            JSONArray ja =
                json.getJSONObject("responseData").getJSONArray("results");

            String title;
            String lat;
            String lng;
            String streetaddress;
            String city;
            String region;
            String country;

            for (int i = 0; i < ja.length(); i++) {
                JSONObject j = ja.getJSONObject(i);

                title = j.getString("titleNoFormatting");
                lat = j.getString("lat");
                lng = j.getString("lng");
                streetaddress = j.getString("streetAddress");
                city = j.getString("city");
                region = j.getString("region");
                country = j.getString("country");

                if (i < 5) {
                    searchResults.add(new Location(title, Float.valueOf(lat), Float.valueOf(lng), streetaddress,                                                   
                                          region, city, country));
                }
                System.out.println(title);
            }            

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        
        return searchResults;
    }
    
    public String prepareDivHtml(List<Location> locList) {
        List<String> divSrc = new ArrayList<String>();
        String innerHtml = "";
            
        if (locList == null || locList.size() == 0)
            return innerHtml;
        
        divSrc.add("<ol style=\"height: 220px; margin: 0; list-style: none; padding:0; font-size: 11px; font-family: Tahoma;\">");
        for (Location loc : locList) {
            divSrc.add("<li style=\"margin-bottom:7px;\">");
            divSrc.add("<a href=\"javascript: alert(1);\" style=\"color: #0000CC;\">");
            divSrc.add(loc.getName());
            divSrc.add("</a>");              
            divSrc.add("<div>");
            divSrc.add(loc.getCountry());
            divSrc.add("</div>");
            divSrc.add("</li>");
        }
        divSrc.add("</ol>");
        /*
        divSrc.add("<div class=\"as_topheader\"></div>");        
        divSrc.add("<div class=\"as_header\">");
        divSrc.add("<div class=\"as_corner\"></div>");
        divSrc.add("<div class=\"as_bar\"></div>");
        divSrc.add("</div>");        
        divSrc.add("<div class=\"as_tb\"></div>");
        divSrc.add("<ul id=\"as_ul\">");
        
        // createMarker(Turkey, Murkey, Adana, Kadana, Badana, Istanbul, Ankara, 10.92103, 10.10212129)
        
        
        int i = 0;
        //function cme(name, latitude, longitude, streetaddress, region, city, country) {        
        for (Location loc : locList) {
            i++;
            String createMarker = "cme(" + String.valueOf(i) + "," + qs(loc.getName()) + "," + loc.getLatitude().toString() + "," + loc.getLongitude().toString() + "," + qs(loc.getStreetaddress()) + "," + qs(loc.getRegion()) + "," + qs(loc.getCity()) + "," + qs(loc.getCountry()) + "); ";
            divSrc.add("<li onclick=\""  + createMarker +" return false;\">");            
            divSrc.add("<a name=\"" + String.valueOf(i) + "\" href=\"#\" onclick=\"" + createMarker + " hideLocationSearchResults(); return false;\">");            
            divSrc.add("<span>" + loc.getName() + ", " + loc.getCity() + "<br>"+ loc.getCountry() + "</br></span>");
            divSrc.add("</a>");
            divSrc.add("</li>");            
            //<em>W</em>
        }                   
                                                                                
        divSrc.add("</ul>");        
        divSrc.add("<div class=\"as_footer\">");                        
        divSrc.add(" <div class=\"as_bar\">");        
        divSrc.add("  <a href=\"#\" onclick=\" hideLocationSearchResults(); return false;\">");            
        divSrc.add("   <span>Close</span>");
        divSrc.add("  </a>");
        divSrc.add(" </div>");        
        divSrc.add("</div>");        
        */
        for (Iterator<String> it=divSrc.iterator(); it.hasNext(); ) {
            innerHtml = innerHtml + it.next();
        }
        
        return innerHtml;
    }
    
    public String qs(String s) {
        return "'" + s + "'";
    }
}
